import Toast from "./Toast";

const {ccclass, property} = cc._decorator;

@ccclass
class ToastManager {

    /**
     * 弹框组件
     * @protected
     */
    protected toastNode: cc.Node

    /**
     * 弹框预制体
     * @protected
     */
    protected toastPrefab: cc.Prefab


    /**
     * 显示弹框
     * @param content
     * @param height
     */
    async show(content: string, height: number = Toast.height) {
        try {
            const hasToast = !!this.toastNode;
            // if (!hasToast) {
            if (!this.toastPrefab) {
                this.toastPrefab = await this.getPrefab('toast')
            }
            this.toastNode = cc.instantiate(this.toastPrefab)
            cc.find('Canvas').addChild(this.toastNode)
            // }
            this.toastNode.getComponent(Toast).init({content, height}).onClose(false)
        } catch (e) {

        }
    }

    close() {
        if (this.toastNode) {
            this.toastNode.getComponent(Toast).onClose()
        }
    }

    /**
     * 获取/assets/resources/prefabs下的预制体组件
     * @param name
     */
    async getPrefab(name: string) {
        return new Promise<cc.Prefab>(resolve => {
            cc.resources.load(`prefabs/${name}`, cc.Prefab, (err, assets: cc.Prefab) => {
                resolve(assets)
            })
        })
    }
}

const toastManager = new ToastManager()
export default toastManager
